package com.idea.relax.log.support;

import com.idea.relax.log.constant.LogConstant;
import com.idea.relax.log.constant.PropsConstant;
import com.idea.relax.log.model.LogCommonModel;
import com.idea.relax.log.support.utils.*;
import lombok.Getter;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @className: AppInfoProvider
 * @description: 设置日志信息的工具类
 * @author: salad
 * @date: 2022/6/1
 **/
@Getter
@Configuration(
        proxyBeanMethods = false
)
public class AppInfoProvider implements SmartInitializingSingleton {

    private static ServerProperties serverProperties;

    private static String hostName;

    private static String ip;

    private static Integer port;

    private static String appName;

    private static String env;


    @Autowired(
            required = false
    )
    public AppInfoProvider(ServerProperties serverProperties, Environment environment) {
        AppInfoProvider.serverProperties = serverProperties;
        AppInfoProvider.appName = environment.getProperty("spring.application.name","");
        AppInfoProvider.env = StringUtil.join(environment.getActiveProfiles());
        AppInfoProvider.port = serverProperties.getPort();
    }


    @Override
    public void afterSingletonsInstantiated() {
        AppInfoProvider.hostName = INetUtil.getHostName();
        AppInfoProvider.ip = INetUtil.getHostIp();
        AppInfoProvider.port = serverProperties.getPort();
    }

    public static void appendRequestInfo(HttpServletRequest request, LogCommonModel model) {
        model.setRequestTime(new Date());
        model.setVisitorIp(WebUtil.getIP(request));
        model.setUserAgent(request.getHeader(PropsConstant.USER_AGENT_HEADER));
        model.setRequestUri(WebUtil.getPath(request.getRequestURI()));
        model.setRequestMethod(request.getMethod());
        model.setRequestParams(WebUtil.getRequestParamToStr(request));
    }

    public static void appendServerInfo(LogCommonModel model) {
        model.setAppName(appName);
        model.setServerName(INetUtil.getHostName());
        model.setServerIp(ip);
        model.setAppPort(port);
        model.setEnv(env);
    }

    public static void appendServerInfoToMdc() {
        MDCUtil.puts(LogConstant.SERVICE_MDC_FIELDS,INetUtil.getHostName(),appName,ip,port,env);
    }

}
